package com.example.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.reggie.common.Result;
import com.example.reggie.dto.DishDto;
import com.example.reggie.entity.Category;
import com.example.reggie.entity.Dish;
import com.example.reggie.entity.DishFlavor;
import com.example.reggie.service.CategoryService;
import com.example.reggie.service.DishFlavorService;
import com.example.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/dish")
public class DishController {

    @Autowired
    private DishService dishService;

    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private CategoryService categoryService;

    @GetMapping("/page")
    public Result<Page> page(int page, int pageSize, String name) {
//        构造分页对象
        Page<Dish> pageInfo = new Page<>(page, pageSize);
        Page<DishDto> pageInfoDto = new Page<>(page, pageSize);
//        构造条件构造器
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
//        添加过滤条件
        queryWrapper.like(StringUtils.isNotEmpty(name), Dish::getName, name);
//        添加排序条件
        queryWrapper.orderByDesc(Dish::getUpdateTime);
//        进行分页查询
        dishService.page(pageInfo, queryWrapper);
//        对象拷贝
        BeanUtils.copyProperties(pageInfo, pageInfoDto, "records");

        List<Dish> records = pageInfo.getRecords();

        List<DishDto> list = records.stream().map((item) -> {
            DishDto dishDto = new DishDto();

            BeanUtils.copyProperties(item, dishDto);

            Long categoryId = item.getCategoryId();

            Category category = categoryService.getById(categoryId);

            if (category != null) {
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }

            return dishDto;
        }).collect(Collectors.toList());

        pageInfoDto.setRecords(list);

        return Result.success(pageInfoDto);
    }

    /**
     * 新增菜品
     *
     * @param dishDto
     * @return
     */
    @PostMapping
    public Result<String> save(@RequestBody DishDto dishDto) {
        log.info("dish:{}", dishDto.toString());
        dishService.saveWithFlavor(dishDto);
        return Result.success("新增菜品成功！");
    }

    /**
     * 获取菜品信息
     */

    @GetMapping("/{id}")
    public Result<DishDto> get(@PathVariable Long id) {

        DishDto dishDto = dishService.getByIdWithFlavor(id);

        return Result.success(dishDto);
    }

    /**
     * 修改菜品信息
     */

    @PutMapping
    public Result<String> update(@RequestBody DishDto dishDto) {
        dishService.updateWithFlavor(dishDto);
        return Result.success("修改菜品成功！");
    }

    /**
     * 根据菜系ID查询菜品列表
     */
    @GetMapping("/list")
    public Result<List<Dish>> list(Dish dish) {
        //构造查询条件
        LambdaQueryWrapper<Dish> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(dish.getCategoryId() != null, Dish::getCategoryId, dish.getCategoryId());
//        只查询正在销售的
        lambdaQueryWrapper.eq(Dish::getStatus, 1);
//        添加排序条件
        lambdaQueryWrapper.orderByAsc(Dish::getSort).orderByAsc(Dish::getUpdateTime);
        return Result.success(dishService.list(lambdaQueryWrapper));
    }

    /**
     * 批量设置菜品状态
     */
    @PostMapping("/status/{status}")
    public Result<String> updateStatus(@PathVariable Integer status, String ids) {
        log.info("status:{},id:{}", status, ids);

        //将字符串分割成数组
        String[] idArr = ids.split(",");
        //遍历数组 逐个修改他们的状态
        for (String id : idArr) {
            Dish dish = new Dish();
            dish.setId(Long.valueOf(id));
            dish.setStatus(status);
            dishService.updateById(dish);
        }

        return Result.success("修改成功！");
    }


    /**
     * 批量删除菜品
     */
    @DeleteMapping
    public Result<String> delete(String ids) {
        String[] idArr = ids.split(",");
//        创建一个可扩展的数组 它将存放没有被使用的菜品ID
        String[] temArr = new String[idArr.length];

        //遍历 idArr 如果有套餐使用了该菜品，不允许删除 需要获取下标
        for (int i = 0; i < idArr.length; i++) {
            LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(DishFlavor::getDishId, idArr[i]);
            int count = (int) dishFlavorService.count(queryWrapper);
            if (count > 0) {
                return Result.error("菜品已被套餐使用，不允许删除！");
            }
//        如果没有被使用，就往 temArr 数组中添加
            temArr[i] = idArr[i];
        }
//        遍历 temArr 数组，删除没有被使用的菜品
        for (String id : temArr) {
            dishService.removeById(id);
        }

        return Result.success("删除成功！");
    }

}
